package cn.com.nes.common.util;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import static cn.com.nes.common.util.Globals.*;

public class OssUtil {

    /**
     * 获取图片签名地址
     * @param imagePath       图片名称
     * @param isYs            0-不压缩，1-压缩
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName      存储的包空间名称
     * @return
     */
    private static String getImgSignURL(String imagePath, int isYs, String endpoint, String accessKeyId,
            String accessKeySecret, String bucketName, String waterMark) {
        // oss客户端

        String urlStr = "";
        OSS ossClient = null;
        try {
            // 创建客户端对象
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 定义过期时间
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            // 判断文件是否存在
            boolean found = ossClient.doesObjectExist(bucketName, imagePath);
            if (found) {
                // 判断是否为图片
                boolean isImage = DBUtils.isPicture(imagePath);
                if (isImage) {
                    // 生成签名以后的URL
                    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, imagePath, HttpMethod.GET);
                    // 设置过期时间
                    req.setExpiration(expiration);
                    String style = "";
                    if (StrUtil.isNotEmpty(waterMark)) {
                        waterMark = Base64.encodeBase64String(waterMark.getBytes("utf-8"))
                                .replace("+", "-")
                                .replace("/", "_");
                    }
                    String syurl = "/watermark,type_ZmFuZ3poZW5nZmFuZ3Nvbmc,size_10,text_" + waterMark + ",color_FFFFFF,shadow_50,t_100,g_north,y_30";
                    // 判断是否压缩
                    switch (isYs) {
                        case 1:
                            style = "image/resize,m_lfit,w_110";
                            break;
                        case 2:
                            style = "image/quality,q_100 ";
                            break;
                        case 3:
                            // 多行水印
                            style = "image/watermark,type_ZmFuZ3poZW5nZmFuZ3Nvbmc,size_20,text_" + waterMark + ",color_efefef,t_80,fill_1,padx_60,pady_60";
                            break;
                        case 4:
                            style = "image/resize,m_lfit,w_110" + syurl;
                            break;
                        case 5:
                            style = "image/quality,q_100" + syurl;
                            break;
                        default:
                            break;
                    }
                    if (!"".equals(style)) {
                        // 设置图片样式
                        req.setProcess(style);
                    }
                    req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                    // 获取图片地址
                    URL signedUrl = ossClient.generatePresignedUrl(req);
                    urlStr = signedUrl.toString();
                } else {
                    throw new Exception("不是图片");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return urlStr;
    }

    /**
     * 获取文件签名地址
     * @param fileName        文件名称
     * @param isYs            0-不压缩，1-压缩
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName      存储的包空间名称
     * @return
     */
    private static String getFileSignURL(String fileName, int isYs, String endpoint, String accessKeyId,
            String accessKeySecret, String bucketName) {
        // oss客户端

        String urlStr = "";
        OSS ossClient = null;
        try {
            // 创建客户端对象
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 定义过期时间
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            // 判断文件是否存在
            boolean found = ossClient.doesObjectExist(bucketName, fileName);
            if (found) {
                // 生成签名以后的URL
                GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
                // 设置过期时间
                req.setExpiration(expiration);
                String style = "";
                // 判断是否压缩
                switch (isYs) {
                    case 1:
                        style = "image/resize,m_lfit,w_110";
                        break;
                    case 2:
                        style = "image/quality,q_100 ";
                        break;
                    default:
                        break;
                }
                if (!"".equals(style)) {
                    // 设置图片样式
                    req.setProcess(style);
                }
                req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                // 获取图片地址
                URL signedUrl = ossClient.generatePresignedUrl(req);
                urlStr = signedUrl.toString();

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return urlStr;
    }

    public static boolean SaveImageFromStream(String path, String filename) {
        OSS ossClient = null;
        try {
            //定义一个URL对象，就是你想下载的图片的URL地址
            URL url = new URL(path);
            //打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为10秒
            conn.setConnectTimeout(10 * 1000);
            //通过输入流获取图片数据
            InputStream is = conn.getInputStream();
            ossClient = new OSSClientBuilder().build(endpoint, Globals.uploadAccessKeyID, Globals.accessKeySecretRoleArn);
            ossClient.putObject(Globals.bucketName, filename, is);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main1(String[] args) {
        SaveImageFromStream("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2Fv2-7843433e624805191f525de689d98b98_1440w.jpg%3Fsource%3D172ae18b&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657956684&t=c9030d1e03350316127c5df8ac64d52f", "crm/file/01.jpg");
    }

    /**
     * 获取图片签名地址
     * @param imageName 图片名称
     * @param type      0-不压缩，1-压缩
     * @return
     */
    public static String getImgSignURL(String imageName, Integer type) {
        return getImgSignUrlDefault(imageName, type);
    }

    /**
     * 获取图片签名地址
     * @param imageName 图片名称
     * @param type      0-不压缩，1-压缩
     * @return
     */
    private static String getImgSignUrlDefault(String imageName, Integer type) {
        return getImgSignURL(imageName, type, bucketName);
    }

    /**
     * 获取图片签名地址
     * @param imageName 图片名称
     * @param type      0-不压缩，1-压缩
     * @param bucket    存储的包空间名称
     * @return
     */
    public static String getImgSignURL(String imageName, Integer type, String bucket) {
        return OssUtil.getImgSignURL(imageName, type, endpoint, Globals.uploadAccessKeyID, accessKeySecretRoleArn, bucket, null);
    }

    public static String getImgSignUrlWithWaterMark(String imageName, Integer type, String bucket, String waterMark) {
        return OssUtil.getImgSignURL(imageName, type, endpoint, Globals.uploadAccessKeyID, accessKeySecretRoleArn, bucket, waterMark);
    }

    public static String getPublicURL(String path) {
        return "https://nes-public.oss-cn-beijing.aliyuncs.com/" + path;
    }

    /**
     * 获取文件签名地址
     * @param fileName 文件名称
     * @param type     0-不压缩，1-压缩
     * @return
     */
    public static String getFileSignURL(String fileName, Integer type) {
        return getFileSignUrlDefault(fileName, type);
    }

    /**
     * 获取文件签名地址-默认
     * @param fileName 文件名称
     * @param type     0-不压缩，1-压缩
     * @return
     */
    private static String getFileSignUrlDefault(String fileName, Integer type) {
        return OssUtil.getFileSignUrl(fileName, type, bucketName);
    }

    /**
     * 获取文件签名地址
     * @param fileName   文件名称
     * @param type       0-不压缩，1-压缩
     * @param bucketName 存储的包空间名称
     * @return
     */
    public static String getFileSignUrl(String fileName, Integer type, String bucketName) {
        return OssUtil.getFileSignURL(fileName, type, endpoint, Globals.uploadAccessKeyID, accessKeySecretRoleArn, bucketName);
    }

    //微信头像直接上传oss
    public static String fileUpload(String type, String fileName, MultipartFile multipartFile) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, Globals.uploadAccessKeyID, Globals.accessKeySecretRoleArn);
        String bucketName = publicBucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setStorageClass(StorageClass.Standard);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicReadWrite);
        }
        InputStream fileInputStream = multipartFile.getInputStream();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(fileInputStream.available());
        objectMetadata.setContentEncoding("utf-8");
        objectMetadata.setContentType(getContentType(type));
        ossClient.putObject(bucketName, fileName, fileInputStream, objectMetadata);
        return fileName;
    }

    /**
     * 根据后缀返回contentType
     * @param FilenameExtension 文件后缀
     * @return String
     */
    private static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xls")) {
            return "application/vnd.ms-excel";
        }
        if (FilenameExtension.equalsIgnoreCase(".xlsx")) {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".rar") || FilenameExtension.equalsIgnoreCase(".zip")) {
            return "application/ostet-stream";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp3")) {
            return "audio/mp3";
        }
        if (FilenameExtension.equalsIgnoreCase(".wma")) {
            return "audio/wma";
        }
        if (FilenameExtension.equalsIgnoreCase(".wav")) {
            return "audio/wav";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp4")) {
            return "video/mp4";
        }
        if (FilenameExtension.equalsIgnoreCase(".flv")) {
            return "video/flv";
        }
        if (FilenameExtension.equalsIgnoreCase(".swf")) {
            return "video/swf";
        }
        if (FilenameExtension.equalsIgnoreCase(".avi")) {
            return "video/avi";
        }
        return "image/jpg";
    }

}
